package com.ggs.starbug.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ggs.starbug.entity.TimerTask;
import com.ggs.starbug.mapper.TimerTaskMapper;
import com.ggs.starbug.service.ITimerTaskService;
import com.google.gson.Gson;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.ggs.starbug.config.rabbitmq.RabbitMQConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Starbug
 * @since 2021-12-27
 */
@Service
public class TimerTaskServiceImpl extends ServiceImpl<TimerTaskMapper, TimerTask> implements ITimerTaskService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Gson gson;

    @Override
    @Transactional
    public TimerTask addTimerTask(TimerTask timerTask) {
        boolean result = this.save(timerTask);
        if (result) {
            rabbitTemplate.convertAndSend(TIMER_TOPIC_EXCHANGE, TIMER_ADD_ROUTING_KEY, timerTask);
        }
        return timerTask;
    }

    @Override
    @Transactional
    public boolean deleteTimerTask(Long id) {
        TimerTask timerTask = this.getById(id);
        boolean result = this.removeById(id);
        if (result) {
            rabbitTemplate.convertAndSend(TIMER_TOPIC_EXCHANGE, TIMER_DELETE_ROUTING_KEY, timerTask);
        }
        return result;
    }

    @Override
    @Transactional
    public boolean updateTimerTask(TimerTask timerTask) {
        boolean result = this.updateById(timerTask);
        if (result) {
            rabbitTemplate.convertAndSend(TIMER_TOPIC_EXCHANGE, TIMER_UPDATE_ROUTING_KEY, timerTask);
        }
        return result;
    }

    @Override
    public boolean addAndTTLTimeQueue(TimerTask timerTask, String ttlTime) {
        return false;
    }

//    @Override
//    public boolean addAndTTLTimeQueue(TimerTask timerTask, String ttlTime) {
//        this.save(timerTask);   //保存到数据库
//        //添加到队列中，定时删除定时任务
//    }

}
